import { createRouter, createWebHistory } from 'vue-router'
import i18n from '../i18n'
import { getStoredLanguage, setLanguage } from '../utils/language'

const routes = [
  {
    path: '/',
    name: 'Home',
    component: () => import('../views/Home.vue')
  },
  {
    path: '/service',
    name: 'Service',
    component: () => import('../views/service/Index.vue')
  },
  {
    path: '/service/expert',
    name: 'ServiceExpert',
    component: () => import('../views/service/Expert.vue')
  },
  {
    path: '/service/video',
    name: 'ServiceVideo',
    component: () => import('../views/service/Video.vue')
  },
  {
    path: '/service/manual',
    name: 'ServiceManual',
    component: () => import('../views/service/Manual.vue')
  },
  {
    path: '/service/feedback',
    name: 'ServiceFeedback',
    component: () => import('../views/service/Feedback.vue')
  },
   {
    path: '/servicefaq',
    name: 'Servicefaq',
    component: () => import('../views/Faq.vue')
  },
  {
    path: '/goods',
    name: 'Goods',
    component: () => import('../views/Goods.vue')
  },
  // ==================== 维修工单模块 ====================
  {
    path: '/repair',
    name: 'Repair',
    component: () => import('../views/repair/Index.vue'),
    meta: { title: 'repair.submit.title' }
  },
  {
    path: '/repair/submit',
    name: 'RepairSubmit',
    component: () => import('../views/repair/Submit.vue'),
    meta: { title: 'repair.submit.title' }
  },
  {
    path: '/repair/track/:caseNo',
    name: 'RepairTrack',
    component: () => import('../views/repair/Track.vue'),
    meta: { title: 'repair.track.title' }
  },
  {
    path: '/repair/my-orders',
    name: 'RepairMyOrders',
    component: () => import('../views/repair/MyOrders.vue'),
    meta: { title: 'repair.myOrders.title' }
  },
  {
    path: '/repair/service-centers',
    name: 'RepairServiceCenters',
    component: () => import('../views/repair/ServiceCenters.vue'),
    meta: { title: 'repair.serviceCenters.title' }
  },
  {
    path: '/repair/quote/:id',
    name: 'RepairQuote',
    component: () => import('../views/repair/QuoteConfirm.vue'),
    meta: { title: 'repair.quote.title' }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 导航守卫，根据URL查询参数切换语言
router.beforeEach((to, from, next) => {
  // 获取URL中的语言参数
  const langParam = to.query.lang
  
  // 如果URL中包含有效的语言参数
  if (langParam && ['zh', 'en'].includes(langParam)) {
    // 更新localStorage
    setLanguage(langParam)
    // 更新i18n
    i18n.global.locale.value = langParam
  } else {
    // 如果URL没有语言参数，但需要保持全局语言状态一致
    const storedLang = getStoredLanguage()
    // 只有当当前语言和存储的语言不同时，才更新
    if (i18n.global.locale.value !== storedLang) {
      i18n.global.locale.value = storedLang
    }
  }
  
  next()
})

export default router 